<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class Uc extends Controller {

    const COOKIEXP = 360000000;

    /**
     * 
     * @param type $ControllerName
     * @param type $Action
     * @param type $QueryString
     */
    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    /**
     * user Home
     */
    public function home() {
        #unset($_COOKIE);
        # setcookie("uid", 100244, time() + Uc::COOKIEXP);
        $Uid = intval(isset($_COOKIE['uid']) ? $_COOKIE['uid'] : 0);
        # echo $_COOKIE['uopenid'];
        $userInfo = new stdClass();
        if ($Uid === 0) {
            if (Controller::inWechat()) {
                $code = WechatSdk::getAccessCode("http://112.124.44.172/wshop/?/Uc/home", "snsapi_userinfo");
                if ($code !== FALSE) {
                    // 获取到accesstoken和openid
                    $WResult = WechatSdk::getAccessToken($code);
                    $Openid = $WResult->openid;
                    $WechatUserInfo = WechatSdk::getUserInfo($WResult->access_token, $WResult->openid);
                    $WechatUserInfo['headimgurl'] = preg_replace("/\/0/", "", $WechatUserInfo['headimgurl']);
                    // 地址
                    $address = $WechatUserInfo['province'] . $WechatUserInfo['city'];
                    // 自动注册
                    $RegSQL = "INSERT INTO clients (client_name,client_sex,client_phone,client_birth,client_address
                    ,client_introducer,client_wechat_openid,client_joindate,client_money)
                    VALUES ('%s',%s,'%s','%s','%s',%s,'%s',CURRENT_DATE(),'%s');";
                    $Uid = $this->Db->query(sprintf($RegSQL, $WechatUserInfo['nickname'], $this->wechatSexConv($WechatUserInfo['sex']), 'NULL', '0000-00-00', $address, 0, $Openid, 0));

                    #echo sprintf($RegSQL, $WechatUserInfo['nickname'], $this->wechatSexConv($WechatUserInfo['sex']), '', '0000-00-00', $address, 0, $Openid, 0);
                    // 如果已经注册，取uid
                    if (!$Uid) {
                        // 这里不能全等
                        $Uid = $this->Db->query("SELECT `client_id` FROM `clients` WHERE `client_wechat_openid` = '$Openid';");
                        $Uid = intval($Uid[0]['client_id']);
                    } else {
                        // 注册成功 返回Uid不为0
                        // 插入client_info头像等数据
                        $RegSQL2 = sprintf("INSERT INTO client_infos (`client_id`,`openid`,`headimg`,`dir_introducer`,`top_introducer`) VALUES (%s,'%s','%s',%s,%s);", $Uid, $WResult->openid, $WechatUserInfo['headimgurl'], 0, 0);
                        $this->Db->query($RegSQL2);
                        // cookie
                    }

                    # echo $WResult->openid;
                    setcookie("uopenid", $WResult->openid, time() + Uc::COOKIEXP);
                    setcookie("uaccesstoken", $WResult->access_token, time() + Uc::COOKIEXP);
                    setcookie("uid", $Uid, time() + Uc::COOKIEXP);

                    // userinfo pass params
                    $userInfo->uid = $Uid;
                    $userInfo->uhead = $WechatUserInfo['headimgurl'];
                    $userInfo->nickname = $WechatUserInfo['nickname'];
                    $userInfo->address = $address;
                }
            }
        } else {
            $this->loadModel('User');
            $this->User->hook(array($this->Db));
            $userInfo = $this->User->getUserInfo($Uid);
            // cookie持久
            setcookie("uopenid", $_COOKIE['uopenid'], time() + Uc::COOKIEXP);
            setcookie("uaccesstoken", $_COOKIE['uaccesstoken'], time() + Uc::COOKIEXP);
            setcookie("uid", $_COOKIE['uid'], time() + Uc::COOKIEXP);
        }

        // 待收货订单计算
        $devliveringCount = $this->Db->query(sprintf("SELECT COUNT(`order_id`) AS `count` FROM `orders` WHERE `status` = 'delivering' AND `client_id` = %s", $Uid));

        $this->Smarty->assign('devliCount', $devliveringCount[0]['count']);
        $this->Smarty->assign('bagRand', intval(rand(1, 3)));
        $this->Smarty->assign('userinfo', (array) $userInfo);
        $this->show();
    }

    /**
     * 
     * @param type $sexInt
     * @return string
     */
    private function wechatSexConv($sexInt) {
        $sex_arr = array('NULL', "'m'", "'f'");
        return $sex_arr[($sexInt ? $sexInt : 0)];
    }

    /**
     * companySpread
     */
    public function companySpread($Query) {
        // 统计数据 
        $openid = $this->getOpenId();
        $spreadData = $this->Db->query("select sum(readi) as readi,sum(turned) as turned from company_spread_record WHERE com_id = '$openid';");
        $spreadData = $spreadData[0];
        $spreadData['turnrate'] = sprintf('%.2f', $spreadData['readi'] > 0 ? ($spreadData['turned'] / $spreadData['readi']) : 0);
        $spreadData['incometot'] = $this->Db->query("SELECT sum(amount) AS amount FROM `company_income_record` WHERE com_id = '$openid';");
        $spreadData['incometot'] = $spreadData['incometot'][0]['amount'];
        $spreadData['incometod'] = $this->Db->query("SELECT sum(amount) AS amount FROM `company_income_record` WHERE com_id = '$openid' AND to_days(date) = to_days(now());");
        $spreadData['incometod'] = $spreadData['incometod'][0]['amount'];
        $this->Smarty->assign('stat_data', $spreadData);
        $this->show();
    }

    /**
     * 
     * @param type $Query
     */
    public function ajaxSpreadList($Query) {
        !isset($Query->page) && $Query->page = 0;

        $OpenId = $this->getOpenId();
        $SQLimit = $Query->page * 20 . "," . 20;
        $SpreadSql = "SELECT * FROM `company_spread_record` WHERE `com_id` = '$OpenId' LIMIT $SQLimit;";
        $SpreadList = $this->Db->query($SpreadSql);

        foreach ($SpreadList as $index => $ls) {
            $_data = $this->Db->query("SELECT * FROM `vProductInfo` WHERE `product_id` = $ls[product_id];");
            #var_dump($_data);
            $SpreadList[$index]['pdata'] = $_data[0];
        }

        $this->Smarty->assign('spreadlist', $SpreadList);
        $this->show();
    }

    /**
     * 订单列表
     * @param type $status
     */
    public function orderlist($Query) {
        !isset($Query->status) && $Query->status = '';
        $this->Db->query('UPDATE `orders` SET `client_id` = (SELECT client_id FROM `clients` WHERE `client_wechat_openid` = `orders`.wepay_openid) WHERE `orders`.client_id IS NULL;');
        $this->Smarty->assign('status', $Query->status);
        $this->show();
    }

    /**
     * Ajax订单列表
     * @param type
     */
    public function ajaxOrderlist($Query) {
        $uid = intval($_COOKIE['uid']);
        !isset($Query->page) && $Query->page = 0;

        $_SQL_limit = $Query->page * 10 . ",10";
        if ($Query->status == '' || !$Query->status) {
            $SQL = sprintf("SELECT * FROM `orders` WHERE `client_id` = %s AND `client_id` <> 0 AND `status` <> 'canceled' ORDER BY `order_time` DESC LIMIT $_SQL_limit", $uid);
        } else {
            $SQL = sprintf("SELECT * FROM `orders` WHERE `status` = '$Query->status' AND `client_id` = %s AND `client_id` <> 0 `status` <> 'canceled' ORDER BY `order_time` DESC LIMIT $_SQL_limit;", $uid);
        }
        # echo $SQL;
        $orders = $this->Db->query($SQL);
        foreach ($orders AS &$_order) {
            $_order['order_time'] = $this->dateTimeFormat($_order['order_time']);
            $_order['data'] = $this->Db->query("SELECT catimg,`pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vProductInfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $_order['order_id']);
            #echo "SELECT `pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vProductInfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $_order['order_id'];
        }
        $this->Smarty->assign('orders', $orders);
        $this->show();
    }

    /**
     * 查看订单详情
     * @param type $orderid
     */
    public function viewOrder($orderid) {
        $this->show();
    }

    /**
     * 
     * @param type $timestamp
     * @return string
     */
    private function dateTimeFormat($timestamp) {
        $timestamp = strtotime($timestamp);
        $curTime = time();
        $space = $curTime - $timestamp;
        //1分钟
        if ($space < 60) {
            $string = "刚刚";
            return $string;
        } elseif ($space < 3600) { //一小时前
            $string = floor($space / 60) . "分钟前";
            return $string;
        }
        $curtimeArray = getdate($curTime);
        $timeArray = getDate($timestamp);
        if ($curtimeArray['year'] == $timeArray['year']) {
            if ($curtimeArray['yday'] == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "今天 {$string}";
            } elseif (($curtimeArray['yday'] - 1) == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "昨天 {$string}";
            } else {
                $string = sprintf("%d月%d日 %02d:%02d", $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
                return $string;
            }
        }
        $string = sprintf("%d年%d月%d日 %02d:%02d", $timeArray['year'], $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
        return $string;
    }

}
